package controllers

import (
	"blog/models"
	"bytes"
	"crypto/md5"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/go-sdk/upyun"
	"math/rand"
	"os"
	"path"
	"strconv"
	"time"
)

type ArticleController struct {
	beego.Controller
}

//文章列表
func (this*ArticleController) List() {
	o := orm.NewOrm()
	page, _ := this.GetInt("page")
	size, _ := this.GetInt("limit")
	startSize := (page-1)*size
	var article []models.Article
	qs := o.QueryTable(new(models.Article))
	count,_ := qs.Count()
	//golang分页page，size和sql对调
	_, err := qs.Limit(size).Offset(startSize).OrderBy("-id").All(&article)
	if err != nil {
		beego.Info("错误信息:",err)
		return
	}
	this.Data["json"] = map[string]interface{}{"code":0,"msg":"请求成功","count":count,"data":article}
	this.ServeJSON()
	return
}

//上传文件
func (c*ArticleController) Upload() {
	//获取上传文件
	file, header, err := c.GetFile("file")
	if err != nil {
		beego.Info("文件上传失败,错误信息:",err)
		return
	}
	defer file.Close();
	ext := path.Ext(header.Filename)
	//验证后缀名是否符合要求
	var AllowExtMap map[string]bool = map[string]bool{
		".jpg":true,
		".jpeg":true,
		".png":true,
	}
	if _,ok:=AllowExtMap[ext];!ok{
		beego.Info("后缀名不符合上传文件要求,错误信息:",err)
		return
	}

	//构造文件名称
	rand.Seed(time.Now().UnixNano())
	randNum := fmt.Sprintf("%d", rand.Intn(9999)+1000 )
	hashName := md5.Sum( []byte( time.Now().Format("2006_01_02_15_04_05_") + randNum ) )

	fileName := fmt.Sprintf("%x",hashName) + ext

	up := upyun.NewUpYun(&upyun.UpYunConfig{
		Bucket:beego.AppConfig.String("Bucket"),
		Operator:beego.AppConfig.String("Operator"),
		Password:beego.AppConfig.String("Password"),
	})

	err = up.Put(&upyun.PutObjectConfig{
		Path:"/image/" + time.Now().Format("2006-01-02/") + fileName,
		Reader:file,
	})
	if err != nil {
		beego.Info("文件上传又拍云OSS失败,错误信息",err)
		return
	}
	upyunPATH := beego.AppConfig.String("upyun") + "/image/" + time.Now().Format("2006-01-02/") + fileName
	jsonStr := map[string]interface{}{"src":upyunPATH}
	c.Data["json"] = map[string]interface{}{"code":0,"msg":"请求成功","data":jsonStr}
	c.ServeJSON()
	return
}

//上传文件
//func (c*ArticleController) Upload() {
//	//获取上传文件
//	file, header, err := c.GetFile("file")
//	if err != nil {
//		beego.Info("文件上传失败,错误信息:",err)
//		return
//	}
//	ext := path.Ext(header.Filename)
//	//验证后缀名是否符合要求
//	var AllowExtMap map[string]bool = map[string]bool{
//		".jpg":true,
//		".jpeg":true,
//		".png":true,
//	}
//	if _,ok:=AllowExtMap[ext];!ok{
//		beego.Info("后缀名不符合上传文件要求,错误信息:",err)
//		return
//	}
//	//创建目录
//	uploadDir := "static/upload/" + time.Now().Format("2006-01-02/")
//	err = os.MkdirAll( uploadDir , 777)
//	if err != nil {
//		beego.Info("创建文件夹失败,错误信息:",err)
//		return
//	}
//	//构造文件名称
//	rand.Seed(time.Now().UnixNano())
//	randNum := fmt.Sprintf("%d", rand.Intn(9999)+1000 )
//	hashName := md5.Sum( []byte( time.Now().Format("2006_01_02_15_04_05_") + randNum ) )
//
//	fileName := fmt.Sprintf("%x",hashName) + ext
//
//	fpath := uploadDir + fileName
//	defer file.Close()//关闭上传的文件，不然的话会出现临时文件不能清除的情况
//	err = c.SaveToFile("file", fpath)
//	if err != nil {
//		beego.Info("错误信息:",err)
//		return
//	}
//	var web = beego.AppConfig.String("web")
//	var buffer bytes.Buffer
//	buffer.WriteString(web)
//	buffer.WriteString("/")
//	buffer.WriteString(fpath)
//	newPath := buffer.String()
//	jsonStr := map[string]interface{}{"src":newPath}
//	c.Data["json"] = map[string]interface{}{"code":0,"msg":"请求成功","data":jsonStr}
//	c.ServeJSON()
//	return
//}

//发表文章
func (this*ArticleController) Add(){
	o := orm.NewOrm()
	var title = this.GetString("title")
	var label = this.GetString("label")
	var sort,_ = this.GetInt("sort")
	var paper = this.GetString("paper")
	var image = this.GetString("image")
	var content = this.GetString("content")

	var startTime = "2006-01-02"

	nowDate := time.Now().Format("2006-01-02")
	createdAt, _ := time.Parse(startTime,nowDate);

	//将内容写入文件
	var t = time.Now().Unix()
	var strT = strconv.FormatInt(t,10)
	//1.拼接文件名
	var buffer bytes.Buffer
	buffer.WriteString("static/article/")
	buffer.WriteString(strT)
	buffer.WriteString(".html")
	fileName := buffer.String()
	//1.判断文件是否存在
	_,err := os.Stat(fileName)
	if err != nil {
		_ ,err = os.Create(fileName)
		if err != nil {
			beego.Info("创建文件失败,错误信息:",err)
			return
		}
	}
	f, err := os.OpenFile(fileName,os.O_RDWR|os.O_CREATE|os.O_TRUNC,0644)
	if err != nil {
		beego.Info("打开文件失败,错误信息:",err)
		return
	}
	//2.关闭文件
	defer f.Close()
	//3.写入文件
	if _,err := f.WriteString(content);err != nil {
		beego.Info("文件写入失败,错误信息:", err)
		return
	}
	//保存数据库
	var article models.Article
	article.Image = image
	article.Title = title
	article.Label = label
	article.Paper = paper
	article.Article = fileName
	article.Sort = sort
	article.Read = 0
	article.Live = 0
	article.Status = 1
	article.Created_at = createdAt
	_, err = o.Insert(&article)
	if err != nil{
		beego.Info("文章发表失败,错误信息:",err)
		return
	}
	this.Data["json"] = map[string]interface{}{"code":200,"msg":"请求成功","data":""}
	this.ServeJSON()
	return
}

